/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.sql.*;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.*;
import model.pojo.*;
import net.tanesha.recaptcha.ReCaptchaResponse;
import net.tanesha.recaptcha.ReCaptchaImpl;

/**
 *
 * @author Admin
 */
@WebServlet(name = "DangKy", urlPatterns = {"/DangKy"})
public class DangKy extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        long current_time = System.currentTimeMillis();
        request.setAttribute("KiemTra", 0);
        
        ArrayList<DanhMucPOJO> danhMucs = DanhMucDAO.getDanhSach();
        request.setAttribute("DanhMucS", danhMucs);
        ArrayList<PhieuPOJO> dsKMt = PhieuDAO.getDanhSachKMHnay3();
        request.setAttribute("PhieuKM", dsKMt);
        
        String tenDN = request.getParameter("tentaikhoan");
        String matkhau = request.getParameter("matkhau");
        String golaiMK = request.getParameter("golaimatkhau");
        String email = request.getParameter("email");
        String dienthoai = request.getParameter("sodienthoai");        
        int thanhpho = 0;
        if(request.getParameter("thanhpho")!=null){
            thanhpho = Integer.parseInt(request.getParameter("thanhpho"));
        }  
        ArrayList<KhuVucPOJO> dsKV = new ArrayList<KhuVucPOJO>();
        dsKV = KhuVucDAO.getDanhSach();
        request.setAttribute("KhuVucS", dsKV);
        
        // Tạo Session đăng nhập cho khách hàng
        KhachHangPOJO ssDangNhap = null;
        if(session.getAttribute("KhachHang")==null)
        {
            ssDangNhap = new KhachHangPOJO();
            session.setAttribute("KhachHang", ssDangNhap);
        }
        else
        {
            ssDangNhap = (KhachHangPOJO)session.getAttribute("KhachHang");
        }
        
        if(request.getParameter("Action")==null)
        {
            request.getRequestDispatcher("/DangKy.jsp").forward(request, response);
        }  
        else if(request.getParameter("Action").equals("Reg"))
        {
            KhachHangPOJO kh_tenDN = new KhachHangPOJO();
            KhachHangPOJO kh_email = new KhachHangPOJO();
            kh_tenDN = KhachHangDAO.KiemTraTenDN(tenDN);
            kh_email = KhachHangDAO.KiemTraEmail(email);
            String Port = ".+@.+\\.[a-z]+";   
            String Port2 = "^[0-9]{1,11}$";
            String remoteAddr = request.getRemoteAddr();
            ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
            reCaptcha.setPrivateKey("6Lf2y8kSAAAAAGxWHIqZaLkr4M2IlpGozVkbjmMR");
            String challenge = request.getParameter("recaptcha_challenge_field");
            String uresponse = request.getParameter("recaptcha_response_field");
            ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
            if(tenDN=="" || matkhau=="" || (matkhau!=""&&!matkhau.equals(golaiMK)) 
                    || email=="" || !Pattern.matches(Port, email) || dienthoai=="" || (dienthoai!="" && !Pattern.matches(Port2, dienthoai))
                    || (tenDN!="" && kh_tenDN.getTenTruyCap()!=null) || (email!="" && kh_email.getTenTruyCap()!=null)
                    || !reCaptchaResponse.isValid() || (matkhau!="" && matkhau.length()<6))
            {    
                if(email=="")
                {
                    request.setAttribute("Error_Email", "Chưa nhập Email");
                }
                if(tenDN=="")
                {
                    request.setAttribute("Error_TenDN", "Chưa nhập tên đăng nhập");
                }
                if(matkhau=="")
                {
                    request.setAttribute("Error_MatKhau", "Chưa nhập mật khẩu");
                }
                if(matkhau!="" && !matkhau.equals(golaiMK))
                {
                    request.setAttribute("Error_MatKhauRe", "Nhập lại mật khẩu không đúng");
                }
                if(matkhau!="" && matkhau.length()<6)
                {
                    request.setAttribute("Error_MatKhau", "Mật khẩu tối thiểu 6 ký tự");
                }
                if(email!="" && !Pattern.matches(Port, email))
                {
                    request.setAttribute("Error_Email", "Không đúng định dạng Email");
                    email="";
                }  
                if(dienthoai=="")
                {
                    request.setAttribute("Error_DT", "Chưa nhập số điện thoại");
                }
                if(dienthoai!="" && !Pattern.matches(Port2, dienthoai))
                {
                    request.setAttribute("Error_DT", "Số điện thoại không hợp lệ");
                    dienthoai="";
                }
                if(tenDN!="" && kh_tenDN.getTenTruyCap()!=null)
                {
                    request.setAttribute("Error_TenDN", "Tên truy cập này đã có người sử dụng");
                }
                if(email!="" && kh_email.getTenTruyCap()!=null)
                {
                    request.setAttribute("Error_Email", "Email này đã có người sử dụng");
                }
                if (!reCaptchaResponse.isValid()) 
                {
                    request.setAttribute("Error_capt", "Nhập không chính xác ký tự");
                }
                KhachHangPOJO kh_temp = new KhachHangPOJO(tenDN,email,dienthoai,thanhpho);
                request.setAttribute("tt-kh", kh_temp);
                request.getRequestDispatcher("/DangKy.jsp").forward(request, response);
            }   
            else
            {  
                String refer = request.getParameter("txtRefer");
                int flag2 = KhachHangDAO.KiemTraTenDN_V2(refer);        
                Timestamp ss = new Timestamp(current_time);
                KhachHangPOJO kh = new KhachHangPOJO();
                kh.setTenTruyCap(tenDN);
                kh.setMatKhau(matkhau);
                kh.setEmail(email);
                kh.setSoDienThoai(dienthoai);
                kh.setMaKhuVuc(thanhpho);
                kh.setNgayDangKy(ss);
                int flag=KhachHangDAO.ThemKhachHang(kh);
                if(flag==-1)
                {
                    request.setAttribute("Error", "Có lỗi xảy ra trong quá trình đăng ký, xin mời bạn đăng ký lại");
                    request.getRequestDispatcher("error.jsp").forward(request, response);
                }
                else
                {
                    if(flag2==1)
                    {
                        NhatKyMoiBanPOJO nk = new NhatKyMoiBanPOJO();
                        nk.setTenDangNhap(refer);
                        nk.setNickDangKy(tenDN);
                        nk.setNgayDangKy(ss);
                        NhatKyMoiBanDAO.Them(nk);
                        KhachHangDAO.CapNhatRefer(refer);
                    }
                    ssDangNhap = KhachHangDAO.DangNhap(tenDN,matkhau);
                    session.setAttribute("KhachHang", ssDangNhap);
                    response.sendRedirect("home?Page=View");
                }

            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
